import React, { useState, useEffect } from 'react';
import axios from 'axios';

const ContinuingEducationForm = ({ applicationId }) => {
    const [continuingEducations, setContinuingEducations] = useState([]);
    const [newEducation, setNewEducation] = useState({
        sequenceNo: '',
        educationType: '',
        trainingInstitution: '',
        courseName: '',
        startDate: '',
        endDate: '',
        hours: 0,
        credits: 0,
        remarks: ''
    });
    const [editingId, setEditingId] = useState(null);

    useEffect(() => {
        const fetchContinuingEducations = async () => {
            try {
                const response = await axios.get(`/api/applications/${applicationId}/continuing-education`);
                setContinuingEducations(response.data);
            } catch (error) {
                console.error('Error fetching continuing educations:', error);
            }
        };

        if (applicationId) {
            fetchContinuingEducations();
        }
    }, [applicationId]);

    const handleChange = (e) => {
        const { name, value } = e.target;
        setNewEducation(prevInfo => ({
            ...prevInfo,
            [name]: value
        }));
    };

    const handleAddOrUpdate = async (e) => {
        e.preventDefault();
        try {
            if (editingId) {
                await axios.put(`/api/applications/${applicationId}/continuing-education/${editingId}`, newEducation);
                alert('继续教育信息更新成功！');
            } else {
                await axios.post(`/api/applications/${applicationId}/continuing-education`, newEducation);
                alert('继续教育信息添加成功！');
            }
            setNewEducation({
                sequenceNo: '',
                educationType: '',
                trainingInstitution: '',
                courseName: '',
                startDate: '',
                endDate: '',
                hours: 0,
                credits: 0,
                remarks: ''
            });
            setEditingId(null);
            const response = await axios.get(`/api/applications/${applicationId}/continuing-education`);
            setContinuingEducations(response.data);
        } catch (error) {
            console.error('Error saving continuing education:', error);
            alert('保存失败，请重试。');
        }
    };

    const handleEdit = (info) => {
        setNewEducation(info);
        setEditingId(info.id);
    };

    const handleDelete = async (id) => {
        try {
            await axios.delete(`/api/applications/${applicationId}/continuing-education/${id}`);
            alert('继续教育信息删除成功！');
            setContinuingEducations(continuingEducations.filter(info => info.id !== id));
        } catch (error) {
            console.error('Error deleting continuing education:', error);
            alert('删除失败，请重试。');
        }
    };

    return (
        <div className="form-container">
            <h3>继续教育情况</h3>
            <form onSubmit={handleAddOrUpdate}>
                <div className="form-group">
                    <label>序号:</label>
                    <input type="text" name="sequenceNo" value={newEducation.sequenceNo} onChange={handleChange} required />
                </div>
                <div className="form-group">
                    <label>学历类型:</label>
                    <input type="text" name="educationType" value={newEducation.educationType} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>培训机构:</label>
                    <input type="text" name="trainingInstitution" value={newEducation.trainingInstitution} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>课程名称:</label>
                    <input type="text" name="courseName" value={newEducation.courseName} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>开始日期:</label>
                    <input type="date" name="startDate" value={newEducation.startDate} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>结束日期:</label>
                    <input type="date" name="endDate" value={newEducation.endDate} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>学时:</label>
                    <input type="number" name="hours" value={newEducation.hours} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>学分:</label>
                    <input type="number" name="credits" value={newEducation.credits} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>备注:</label>
                    <textarea name="remarks" value={newEducation.remarks} onChange={handleChange}></textarea>
                </div>
                <button type="submit">{editingId ? '更新' : '添加'}</button>
            </form>

            <h4>已添加继续教育信息</h4>
            <table>
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>学历类型</th>
                        <th>培训机构</th>
                        <th>课程名称</th>
                        <th>开始日期</th>
                        <th>结束日期</th>
                        <th>学时</th>
                        <th>学分</th>
                        <th>备注</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {continuingEducations.map(info => (
                        <tr key={info.id}>
                            <td>{info.sequenceNo}</td>
                            <td>{info.educationType}</td>
                            <td>{info.trainingInstitution}</td>
                            <td>{info.courseName}</td>
                            <td>{info.startDate}</td>
                            <td>{info.endDate}</td>
                            <td>{info.hours}</td>
                            <td>{info.credits}</td>
                            <td>{info.remarks}</td>
                            <td>
                                <button onClick={() => handleEdit(info)}>编辑</button>
                                <button onClick={() => handleDelete(info.id)}>删除</button>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
};

export default ContinuingEducationForm;

